package com.it.schoolbookshop_back.config;

import com.it.schoolbookshop_back.interceptors.JwtInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import jakarta.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;

/**
 * Web 配置类
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);
    
    @Autowired
    private JwtInterceptor jwtInterceptor;
    
    // 不需要验证的接口路径
    private static final List<String> WHITE_LIST = Arrays.asList(
            "/api/user/login",
            "/api/user/register",
            "/api/login",                // 添加登录API
            "/api/register",             // 添加注册API
            "/api/public/**",            // 添加公共API
            "/api/books/public/**",      // 添加公共图书API
            "/swagger-ui/**",            // Swagger UI
            "/swagger-resources/**",     // Swagger 资源
            "/v3/api-docs/**"            // OpenAPI规范
    );
    
    @PostConstruct
    public void init() {
        System.out.println("========= WebConfig已初始化 =========");
        logger.info("========= WebConfig已初始化 =========");
        System.out.println("JWT拦截器: " + (jwtInterceptor != null ? "已注入" : "注入失败"));
        logger.info("JWT拦截器: {}", (jwtInterceptor != null ? "已注入" : "注入失败"));
        System.out.println("白名单路径: " + WHITE_LIST);
        logger.info("白名单路径: {}", WHITE_LIST);
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        System.out.println("========= 添加拦截器 =========");
        logger.info("========= 添加拦截器 =========");
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/api/**")  // 拦截所有 /api 开头的请求
                .excludePathPatterns(WHITE_LIST);  // 排除白名单中的请求
        System.out.println("JWT拦截器已添加，拦截路径: /api/**，排除路径: " + WHITE_LIST);
        logger.info("JWT拦截器已添加，拦截路径: /api/**，排除路径: {}", WHITE_LIST);
    }
    
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
} 